package com.administration.managedBean;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import com.administration.controller.AdministrationController;
import com.administration.entity.User;
import com.common.Utility;
import com.core.managedBean.BaseBean;
import com.entity.RegisteredUser;

@ManagedBean
@ViewScoped
public class ChangePasswordBean extends BaseBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private String oldPassword = "";
	private String password1;
	private String password2;
	AdministrationController administrationController;;
	@PostConstruct
	public void loadData(){
		if (administrationController == null) {
			administrationController = new AdministrationController();
		}
		
	}

	public void changePassword() {
		try {
			RegisteredUser registeredUser = (RegisteredUser) super
					.getSessionAttribute("registeredUser");
			if (registeredUser != null) {
				User dbUser;
				dbUser = administrationController.getUserById(registeredUser
						.getUserId());
				if (!dbUser.getPassword().equals(this.oldPassword)) {
					super.addErrorMessage("Old Password Incorrect");
					return;
				}
				String encPass = Utility.PasswordEncrypt(password1);
				dbUser.setPassword(encPass);
				administrationController.updateUser(dbUser);
				super.addInfoMessage("successfully changed password");
			}
		} catch (Exception e) {
			super.addErrorMessage("Please Check your internet/database connection");
		}

	}

	public String toUserIndex() {
		return "toUserIndex";
	}

	// --------//
	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setPassword1(String password1) {
		this.password1 = password1;
	}

	public String getPassword1() {
		return password1;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String getPassword2() {
		return password2;
	}

}
